package com.kingyea.app.market.file.controller;

import com.kingyea.app.market.Preconditions;
import com.kingyea.app.market.file.bean.File;
import com.kingyea.app.market.file.service.FileService;
import com.kingyea.app.market.utils.GlobalVar;
import com.kingyea.app.market.utils.StateCode;
import com.kingyea.app.market.utils.StringUtils;
import com.kingyea.app.market.utils.UploadUtils;
import com.kingyea.mobilepolice.system.Result;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author CXC
 * @version v1.0.0
 * @description File 控制层
 * @date Created in 2018-03-22 16:52:24
 */
@Api(value = "file ", description = " file ")
@RequestMapping(value = "/file")
@RestController
public class FileController {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private FileService fileService;

    /**
     * 查询全部
     *
     * @param
     * @return /*
     */
    @ApiOperation(value = "带条件统计接口数量", notes = "", response = Result.class)
    @ApiImplicitParams({@ApiImplicitParam(paramType = "body", dataType = "File", name = "file", value = "文件上传：文件对象，系统序号sys，模块序号module，关联对象主键keyId", required = true)})
    @ApiResponses({@ApiResponse(code = 200, message = "请求正常，返回Result对象"),
            @ApiResponse(code = 500, message = "服务器异常")})
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public Object list(@RequestBody File file) throws Exception {
        validation(file);
        return fileService.list(file).stream().map(f -> getFileUri(f)).collect(Collectors.toList());
    }


    /**
     * 创建
     *
     * @param file
     * @return
     */
   /* @ApiImplicitParams({ @ApiImplicitParam(paramType = "form", dataType = "MultipartFile", name = "file", value = "文件上传：文件对象，系统序号sys，模块序号module，关联对象主键keyId", required = true) })
    @ApiResponses({ @ApiResponse(code = 100101, message = "文件uri地址"),
            @ApiResponse(code = 103002, message = "文件上传失败")})*/
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public Object create(@RequestParam(value = "file", required = true) MultipartFile file
            , @RequestParam(value = "sys", required = false) Integer sys
            , @RequestParam(value = "module", required = false) Integer module) throws Exception {
        LOGGER.info("【文件正在上传...】", file);
        File fileBean = new File();
        fileBean.setSys(Optional.ofNullable(sys).orElse(1));
        fileBean.setModule(Optional.ofNullable(module).orElse(1));

        validation(fileBean);
        Preconditions.checkArgument(!file.isEmpty(), StateCode.FILE_SELECT_NULL_ERROR);

        System.out.println(file.getOriginalFilename());
        fileBean.setFileSize(Long.valueOf(file.getSize()).intValue());
        fileBean.setCreateDate(new Date());
        fileBean.setHost(GlobalVar.FILE_HOST);
        fileBean.setUrl(GlobalVar.getFileUrl(fileBean.getModule()));
        //fileBean.setKeyName(UUID.randomUUID().toString());
        fileBean.setOldName(file.getOriginalFilename());
        fileBean.setSufName(file.getOriginalFilename().substring(file.getOriginalFilename().indexOf(".")));
        fileBean.setUrl(GlobalVar.getFileUrl(module));

        java.io.File localFile = UploadUtils.uploadFile(file, new StringBuilder().append(GlobalVar.FILE_DIR).append(fileBean.getUrl()).toString());
        fileBean.setKeyName(localFile.getName());

        Preconditions.checkArgument(fileService.save(fileBean), StateCode.FILE_UPLOAD_FAIL_ERROR);
        LOGGER.info("【文件上传成功】", file);
        return fileBean;
    }

    /**
     * 多文件上传
     *
     * @param file   该命名根据elementui 的上传控件来命名的，不能改
     * @param sys
     * @param module
     * @return java.lang.Object
     * @author Mr.Lin
     * @date 2018/3/24 16:13
     */  
   /* @ApiImplicitParams({ @ApiImplicitParam(paramType = "form", dataType = "MultipartFile", name = "file", value = "文件上传：文件对象，系统序号sys，模块序号module，关联对象主键keyId", required = true) })
    @ApiResponses({ @ApiResponse(code = 100101, message = "文件uri地址"),
            @ApiResponse(code = 103002, message = "文件上传失败")})*/
    @RequestMapping(value = "/uploads", method = RequestMethod.POST)
    public Object create(@RequestParam("file") MultipartFile[] file
            , @RequestParam("sys") Integer sys
            , @RequestParam("module") Integer module) throws Exception {
        List<File> fileList = new ArrayList<>();
        for (MultipartFile elemFile : file) {
            fileList.add((File) create(elemFile, sys, module));
        }
        return fileList;
    }


    /**
     * 删除
     *
     * @return
     */
    /*@ApiOperation("删除一个文件记录")
    @ApiResponses({ @ApiResponse(code = 100101, message = "true"),
            @ApiResponse(code = 103003, message = "文件删除失败")})
    @ApiImplicitParams({ @ApiImplicitParam(paramType = "body", dataType = "File", name = "file", value = "文件定义属性：文件系统序号sys，系统模块module，模块对象主键keyId，定位到一个文件url（可选参数）", required = true) })*/
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Object delete(@RequestBody File file) throws Exception {
        file.setSys(Optional.ofNullable(file.getSys()).orElse(1));
        file.setModule(Optional.ofNullable(file.getModule()).orElse(1));
        validation(file);
        LOGGER.info("【文件正在删除...】", file);
        file.setKeyName(StringUtils.getUrlFileName(file.getUrl()));
        file.setUrl(null);
        Preconditions.checkArgument(fileService.delete(file), StateCode.FILE_DELETE_FAIL_ERROR);
        LOGGER.info("【文件删除成功】", file);
        return true;
    }

    private void validation(File file) {
        Preconditions.checkNotNull(file.getSys(), StateCode.SYSTEM_ERROR);
        Preconditions.checkNotNull(file.getModule(), StateCode.SYSTEM_ERROR);
//        Preconditions.checkNotNull(file.getKeyId(), StateCode.FILE_SELECT_NULL_ERROR);
        Preconditions.checkArgument(GlobalVar.supportSys(file.getSys()), StateCode.SYS_NOT_SUPPORT_ERROR);
        Preconditions.checkArgument(GlobalVar.supportModule(file.getModule()), StateCode.MODULE_NOT_SUPPORT_ERROR);
    }

    private String getFileUri(File fileBean) {
        return new StringBuilder().append(fileBean.getHost()).append(fileBean.getUrl()).append(fileBean.getKeyName()).toString();
    }

}
